package logic

import (
	"context"
	"house/pkg"
	"net/http"
	"path"

	"api/internal/svc"
	"api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UploadLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUploadLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UploadLogic {
	return &UploadLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UploadLogic) Upload(req *http.Request) (resp *types.Response, err error) {
	// todo: add your logic here and delete this line
	file, m, err := req.FormFile("image")
	if err != nil {
		return nil, err
	}
	upload, err := pkg.Upload(file, m)
	if err != nil {
		return &types.Response{
			Code:     500,
			Messages: err.Error(),
			Data:     nil,
		}, nil
	}
	if m.Size > 5*1024*1024 {
		return &types.Response{
			Code:     500,
			Messages: "文件过大",
			Data:     nil,
		}, nil
	}
	suffix := map[string]bool{
		".png": true,
		".jpg": true,
		"jpeg": true,
	}
	ext := path.Ext(m.Filename)
	if suffix[ext] == false {
		return &types.Response{
			Code:     500,
			Messages: "文件格式必须是。png.jpg.jpeg",
			Data:     nil,
		}, nil
	}
	return &types.Response{
		Code:     500,
		Messages: "发送成功",
		Data:     upload,
	}, nil
}
